package org.example.blog_manage.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cglib.proxy.Enhancer;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;



public class jwt {

    private static final long  EXPIRATION_TIME  = 100*1000;
    String strKey = "OPTf4EqCAQe75G0XM80DkyiqlIrIEBkn47YexX9a7Nt43Ig8kcVsmES340q8yntV";
    Key key = Keys.hmacShaKeyFor(strKey.getBytes());


    /*
    * 自己生成一个key
    * */
    @Test
    public void genKey(){
        String strKey = "dhiadfsefserfsfefesfefsfsefes3euhwu";
        Key key = Keys.hmacShaKeyFor(strKey.getBytes());
        String strKey1 = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(strKey1);
    }

    /*
    * 官方生成key(每一次的生成都不一样)
    * */
    @Test
    public void genKey1(){
        //自动生成key
        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS384);
        //转换为字节数组，再转换为字符串
        String strKey = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(strKey);
    }

    /*
    * 根据key生成token
    * */
    @Test
    public void genJwt(){
        //设为全局变量
        String strKey = "OPTf4EqCAQe75G0XM80DkyiqlIrIEBkn47YexX9a7Nt43Ig8kcVsmES340q8yntV";
        Key key = Keys.hmacShaKeyFor(strKey.getBytes());

        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","lisi2");

        String str = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
                .signWith(key)
                .compact();

        System.out.println(str);
    }

    /*
    * 校验功能
    * */
    @Test
    public void parseToken(){

        String token = "eyJhbGciOiJIUzUxMiJ9.eyJuYW1lIjoibGlzaTIiLCJpZCI6MSwiZXhwIjoxNzQ4NTI5MTAxfQ.OriDTSyukGNcfeaOmMDRd4XWFtZRSDlJ7FkOdSCMP0vSCU6P0dXDsmkn3hb294biUqh-1Dfta12wFQHtnGvLAg";

//        创建JWT解析器(根据这个key，创建出专属的解析器)
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
//        根据解析器解析令牌并得到载荷部分
        Claims body = build.parseClaimsJws(token).getBody();
        System.out.println(body);
    }

}
